package com.tjbklx1.thread.chap04.practise04;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.tjbklx1.thread.chap03.demo01.Request;

public class RequestQueue3 {

//	private final Queue<Request> queue = new LinkedList<Request>();
	private final BlockingQueue<Request> queue= new LinkedBlockingQueue<Request>();

	public synchronized Request getRequest() { // 注意同步
		Request request =null;
		
		try {
			//request = queue.take();
			//TIMOUT
			request = queue.poll(30L, TimeUnit.SECONDS);
			//NEW ADD TIMEOUT 
			if(request == null){
				throw new LivenessException("throw by :"+Thread.currentThread().getName());
			}
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		return request;
		
//		while (queue.peek() == null) {
//			try {
//				System.out.println(Thread.currentThread().getName() + " : wait() begins,queue = " + queue);
//				wait();
//				System.out.println(Thread.currentThread().getName() + " : wait() ends,queue = " + queue);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		}
//		return queue.remove();
	}

	public synchronized void putRequest(Request request) { // 注意同步
		try {
//			queue.take();
			boolean offered = queue.offer(request, 30L, TimeUnit.SECONDS);
			if(!offered){
				throw new LivenessException("throw by :"+Thread.currentThread().getName());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
//		queue.offer(request);
//		System.out.println(Thread.currentThread().getName() + " : notifyAll() begins,queue = " + queue);
//		notifyAll();
//		System.out.println(Thread.currentThread().getName() + " : notifyAll() ends,queue = " + queue);
	}
}
